package com.dycong.common.IO.netty.frame_coder;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Created by dycong on 2017/3/13.
 */
public class EchoClientHandler extends ChannelInboundHandlerAdapter {

    static int count = 0;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        this.channel = ctx;
        String msg="asdfghghf321456987";
        Msg m=new Msg();
        m.setBody(msg);
        m.setLength(msg.length());
        ctx.writeAndFlush(m);
        System.out.println("connect..........................................");
    }
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelRegistered();
        String msg="asdfghghf321456987";
        Msg m=new Msg();
        m.setBody(msg);
        m.setLength(msg.length());
        ctx.writeAndFlush(m);
        System.out.println("Registered..........................................");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx,
                               Object msg) throws Exception {
        Msg msg1=(Msg)msg;
        System.out.println("ClientReader received: " + msg1.toString());
//        ctx.writeAndFlush(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,
                                Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    ChannelHandlerContext channel;

    public boolean sendMsg(String msg) {
        System.out.println("客户端发送消息：" + msg);
        Msg m=new Msg();
        m.setBody(msg);
        m.setLength(msg.length());
        channel.writeAndFlush(m);
        return msg.equals("q") ? false : true;
    }
}
